/**
 * 用户管理脚本
 */
(function() {
	/***************************************************************************
	 * 页面初始化
	 */
	// document.onkeydown = function(e) {
	// platform.forbiddenEnter(e);
	// }
	window.onload = function() {
		dishList.init();
	};
	/***************************************************************************
	 * dishGridView
	 */
	var dishList = {
		dishTypeOpts: ko.observableArray(),
		init: function() {
			var that = this;
			var result = JSON.parse(platform.servicebreak('~/rest/pubcode/options', {
				p_code_id: '0dd61253-2206-488d-a017-d61a46cac826'
			}).responseText);
			var resultCode = JSON.parse(platform.servicebreak('~/rest/pubcode/selectByCond', {
				p_code_id: '0dd61253-2206-488d-a017-d61a46cac826'
			}).responseText);
			if(result instanceof Object && result.length > 0) {
				$.each(result, function(index, node) {
					that.dishTypeOpts.push(node);
				});
			}
			var columns = [{
					checkbox: true,
					field: 'checkbox',
					align: 'center',
					valign: 'middle'
				},
				{
					field: 'goods_id',
					title: '主键标识',
					width: 250,
					valign: 'middle',
					align: 'center',
					visible: false,
				},
				{
					field: 'goods_name',
					title: '菜品名',
					width: 120,
					valign: 'middle'
				},
				{
					field: 'goods_price',
					title: '菜品价格',
					width: 80,
					valign: 'middle'
				},
				{
					field: 'goods_class',
					title: '菜品分类',
					width: 180,
					formatter: function(value, data, index) {
						for(var i = 0; i < result.length; i++) {
							if(result[i].code_id == value) {
								return result[i].code_text;
							}
						}
					}
				}, {
					field: 'goods_info',
					title: '菜品信息',
					width: 120
				}
			];
			$('#tb_dishes').bootstrapTable({
				url: platform.mapUrl('~/rest/goods/selectByCond'),
				cache: false,
				method: 'post',
				contentType: 'application/json',
				dataType: 'json',
				search: false,
				strictSearch: true,
				singleSelect: false,
				striped: true,
				showFooter: false,
				showToggle: false,
				showRefresh: true,
				showPaginationSwitch: false,
				silent: true,
				pagination: true,
				sidePagination: 'server',
				pageNumber: 1,
				pageSize: 10,
				pageList: [10, 15, 20, 50],
				queryParams: function(params) {
					return {
						pageNumber: params.offset / params.limit + 1,
						pageSize: params.limit,
						shop_person: platform.getCurrentUser().user_id
					}
				},
				clickToSelect: true,
				height: 504,
				uniqueId: 'user_id',
				userView: false,
				cardView: false,
				toolbar: '#toolbar',
				columns: columns
			}).bootstrapTable('hideColumn', 'goods_id');
		},
		fnAdd: function() {
			myDishAdd.clear();
			var form = myDishAdd;
			$('#detailForm')[0].reset();
			form.uv_goodsId(platform.uuid());
			form.uv_shopId(methods.getShop().shop_id);
			var oFileInput = new FileInput();
			//上传图片控件 初始化
			oFileInput.Init("uv_dishPic", platform.mapUrl('~/rest/goods/uploadFile'));
			/*.mapUrl('~/rest/goods/uploadFile?goods_id=' +
				form.uv_goodsId() + '&goods_name=' +
				form.uv_dishName() + '&goods_price=' +
				form.uv_dishPrice() + '&goods_class=' +
				form.uv_dishClass() + '&goods_info=' +
				form.uv_dishInfo() +
				'&shop_id=' + form.uv_shopId()));*/
			$('#myDishAdd').modal('show');
		},
		fnRemove: function() {
			var result = platform.checkSelectedYzw('tb_dishes', 'remove');
			if(result) {
				var goods = $('#tb_dishes').bootstrapTable('getSelections');
				var params = {};
				var goodIds = [];
				for(var i = 0; i < goods.length; i++) {
					goodIds.push(goods[i].goods_id);
				}
				params.goods_id = goodIds;
				methods.del(params);
			}
		},
		fnEdit: function() {
			var result = platform.checkSelected('tb_dishes', 'EDIT');
			if(result) {
				var form = myDishModify;
				form.clear();
				var oFileInput = new FileInput();
				oFileInput.Init("uv_dishModifyPic", platform.mapUrl('~/rest/goods/uploadFile')); 
				myDishModify.showViewForm($('#tb_dishes').bootstrapTable(
					'getSelections')[0].goods_id);  
			}
		},
		fnTC: function() {

		},
		fnZK: function() {

		},
		fnFL: function() {

		}
	};
	ko.applyBindings(dishList, document.getElementById('dishGridView'));
	/*
	 * 商品新增模态框
	 */
	var myDishAdd = {
		uv_goodsId: ko.observable(''),
		uv_shopId: ko.observable(''),
		uv_dishName: ko.observable(''),
		uv_dishClass: ko.observable(''),
		uv_dishPrice: ko.observable(''),
		uv_dishPic: ko.observable(''),
		uv_dishInfo: ko.observable(''),
		dishTypeSelected: ko.observable(),
		dish_options: ko.computed(function() {
			return dishList.dishTypeOpts();
		}, this),
		clear: function() {
			this.uv_goodsId('');
			this.uv_shopId('');
			this.uv_dishName('');
			this.uv_dishPrice('');
			this.uv_dishClass('');
			this.uv_dishPic('');
			this.uv_dishInfo('');
		},
		funAdd: function() {
			$('#uv_dishPic').fileinput('upload');
		}
	};
	ko.applyBindings(myDishAdd, document.getElementById('myDishAdd'));
	/*
	 * 商品修改模态框
	 */
	var myDishModify = {
		uv_goodsId: ko.observable(''),
		uv_shopId: ko.observable(''),
		uv_dishName: ko.observable(''),
		uv_dishClass: ko.observable(''),
		uv_dishPrice: ko.observable(''),
		uv_dishPic: ko.observable(''),
		uv_dishInfo: ko.observable(''),
		dishTypeSelected: ko.observable(),
		dish_options: ko.computed(function() {
			return dishList.dishTypeOpts();
		}, this),
		clear: function() {
			this.uv_goodsId('');
			this.uv_shopId('');
			this.uv_dishName('');
			this.uv_dishPrice('');
			this.uv_dishClass('');
			this.uv_dishPic('');
			this.uv_dishInfo('');
		},
		resetForm: function() {
			if($('#detailForm').data('bootstrapValidator') != null ||
				$('#detailForm').data('bootstrapValidator') != undefined) {
				$('#detailForm').data('bootstrapValidator').resetForm();
			}
		},
		showViewForm: function(pid) {
			var result = methods.get(pid);
			var form = myDishModify;
			form.clear();
			form.resetForm();
			form.uv_goodsId(result.goods_id);
			form.uv_shopId(result.shop_id);
			form.uv_dishName(result.goods_name);
			form.uv_dishPrice(result.goods_price);
			form.uv_dishClass(result.goods_class);
			// form.uv_dishPic(result.goods_picture);
			form.uv_dishInfo(result.goods_info);
			$('#myDishModify').modal('show');
		},
		funModify: function() {
			$('#uv_dishPic').fileinput('upload');
		}
	};
	ko.applyBindings(myDishModify, document.getElementById('myDishModify'));
	/*
	 * 图片上传
	 */
	var FileInput = function() {
        var oFile = {};

		// 初始化fileinput控件（第一次初始化）
		oFile.Init = function(ctrlName, uploadUrl) {
			var control = $('#' + ctrlName);

			// 初始化上传控件的样式
			control.fileinput({
				language: 'zh', // 设置语言
				uploadUrl: uploadUrl, // 上传的地址
				allowedFileExtensions: ['jpg', 'gif', 'png'], // 接收的文件后缀
				showUpload: false, // 是否显示上传按钮
				showCaption: false, // 是否显示标题
				showUploadedThumbs: false,
				browseClass: "btn btn-primary", // 按钮样式
				uploadAsync: true,
				autoReplace: true,
				overwriteInitial: true,
				// dropZoneEnabled: false,//是否显示拖拽区域
				// minImageWidth: 50, //图片的最小宽度
				// minImageHeight: 50,//图片的最小高度
				// maxImageWidth: 1000,//图片的最大宽度
				// maxImageHeight: 1000,//图片的最大高度
				// maxFileSize: 0,//单位为kb，如果为0表示不限制文件大小
				// minFileCount: 0,
				maxFileCount: 3, // 表示允许同时上传的最大文件个数
				enctype: 'multipart/form-data',
				validateInitialCount: true,
				previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
				msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
				fileActionSettings: {
					showUpload: false,
					showRemove: false
				},
				uploadExtraData: function(previewId, index) {
					var param = {};
					param.goods_id = document.getElementById('goods_id').value;
					param.goods_name = document.getElementById('goods_name').value;
                    param.goods_class = document.getElementById("goods_class").value;
					param.goods_price = document.getElementById('goods_price').value;
					param.goods_class = document.getElementById('goods_class').value;
					param.goods_info = document.getElementById('goods_info').value;
					param.shop_id = document.getElementById('shop_id').value;
					return param;
				}
			});
        };
		return oFile;
	};
	/*
	 * 删除获取方法
	 */
	var methods = {
		del: function(params) {
			// if (selections[0].user_name == $.cookie('_curUser')) {
			// platform.showErrorTip('已阻止试图删除当前登录用户的操作');
			// return;
			// }
			platform.servicebreakAsync('~/rest/goods/delete', params, 'post')
				.done(function(response) {
					if(response.success) {
						$('#tb_dishes').bootstrapTable('refresh');

                    } else {

                    }
				});
		},
		getShop: function() {
			var param = {};
			param.shop_person = platform.getCurrentUser().user_id;
			var result = JSON2.parse(platform.servicebreak(
				'~/rest/shop/selectOne', param).responseText);
			return result;
		},
		get: function(pid) {
			var param = {};
			param.goods_id = pid;
			var result = JSON2.parse(platform.servicebreak(
				'~/rest/goods/selectone', param).responseText);
			return result;
		},
		save: function(param) {
			platform.servicebreakAsync('~/rest/user/save', param, 'post',
				function() {
					platform.showOperTip('dealing');
				}).done(function() {
				$('#tb_users').bootstrapTable('refresh');
			});
		}
	}
})(this);